import React, { Component } from 'react';
// 验证码组件
import axios from 'axios'

// 引入校验规则
import Pts from 'prop-types'
class Captcha extends Component {
    state = {
        imgUrl: ''  // 验证码图片地址
    }
    //定义默认的props
    static defaultProps = {
        w: '140px',
        h: '40px'
    }

    // 对父组件中传递给我当前组件的参数进行类型校验
    static propTypes = {
        getKey: Pts.func.isRequired
    }

    // 点击刷新验证码
    loadRefresh = () => {
        this.loadCaptcha()
    }
    // 验证码请求
    loadCaptcha = () => {
        axios.get('https://reactapi.iynn.cn/captcha/api/math').then(res => {
            // console.log(res);
            this.setState({
                imgUrl: res.data.img
            }, () => {
                this.props.getKey(res.data.key)
            })
        }).catch(e => { })
    }
    render() {
        return (
            <div onClick={this.loadRefresh}>
                <img src={this.state.imgUrl} width={this.props.w} height={this.props.h} />
            </div>
        );
    }
    componentDidMount() {
        //初始化调用
        this.loadCaptcha()
    };

}

export default Captcha;
